package data

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"hotMoney/config"
	"hotMoney/model"
	"time"
)

var Db *gorm.DB

func InitMysql(conf config.AppConfig) {
	fmt.Println("Load dbService config...")

	//配置mysql连接相关信息
	dbType := conf.App.Database.Type
	usr := conf.App.Database.User
	pwd := conf.App.Database.Password
	address := conf.App.Database.Address
	dbName := conf.App.Database.DbName
	dbLink := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		usr, pwd, address, dbName)
	var err error
	//创建一个数据库连接,循环尝试连接
	for Db, err = gorm.Open(dbType, dbLink); err != nil; Db, err = gorm.Open(dbType, dbLink) {
		fmt.Println("Failed to connect database: ", err.Error())
		fmt.Println("Reconnecting in 5 seconds...")
		time.Sleep(5 * time.Second)
	}
	Db.DB().SetMaxOpenConns(conf.App.Database.MaxOpen)
	Db.DB().SetMaxIdleConns(conf.App.Database.MaxIdle)


	//创建user表和reward表

	//设置表明不为复数
	Db.SingularTable(true)

	//创建user对象和积分对象
	Db.AutoMigrate(&model.User{}, &model.Reward{}, &model.RewardInfo{})



}
